#!/bin/bash 
# 设置命令标题名称
echo -ne "\e]2;银河麒麟V10Sp1工具箱\a"

# 确保脚本在终端中运行
if [ -z "$TERM" ]; then
    # 如果没有终端，尝试启动一个终端来运行脚本
    x-terminal-emulator -e "$0"
    exit 0
fi

# 颜色定义
red='\033[0;31m' 
green='\033[0;32m' 
yellow='\033[0;33m'
blue='\033[0;34m' 
cyan='\033[0;36m'
magenta='\033[0;35m' 
reset='\033[0m'
nc='\033[0m'

# 优化图标路径检查
icon_path="/usr/share/icons/hicolor/48x48/apps/xq-kylin-tools.png"
[[ ! -f "$icon_path" ]] && icon_path=""  # 图标不存在时不显示

# ====================== 通知工具函数 ======================
# 桌面通知与终端提示函数
show_notification() { 
    local title="$1" message="$2" level="$3" icon="${4:-}"
    case "$level" in
        "success") color="$green"; urgency="normal" ;;
        "warning") color="$yellow"; urgency="normal" ;;
        "error")   color="$red"; urgency="critical" ;;
        *)         color="$nc"; urgency="normal" ;;
    esac
    echo -e "\n${color}【$title】${message}${NC}"
    # 发送桌面通知
    if command -v notify-send &> /dev/null; then
        if [[ -n "$icon" && -f "$icon" ]]; then
            notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
        else
            notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
        fi
    fi
}

# ====================== 权限检查与获取函数 ======================
# 错误处理函数 - 防止闪退并提示用户
handle_error() {
    local message="$1"
    echo -e "\n${red}【错误】${message}${NC}"
    show_notification "操作失败" "${message}" "error" "$icon_path"
    read -p "按Enter键继续或关闭窗口..."  # 防止闪退，等待用户确认
}
echo -e "${blue}▶ 正在验证sudo权限，请输入您的密码...${NC}"

if sudo -v; then
    echo -e "\n${green}【成功】sudo权限验证通过，继续执行后续操作${NC}"
else
    echo -e "\n${red}【错误】sudo权限验证失败！原因可能是：${NC}" 
    echo -e "${yellow}1. 当前用户未配置sudo权限"
    echo -e "2. 密码输入错误"
    exit 1
fi

# 用户确认函数：提示用户确认操作（y/n），返回 0（确认）或 1（取消）
confirm_operation() {
    echo -en "${yellow}$1 (y/n): ${reset}"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]] && return 0 || return 1  
}


# ====================== 4）系统信息菜单开始 ======================
# 系统信息菜单：查看系统信息和快捷键
system_info_menu() {
    while true; do
        clear
        echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"        
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                           系统信息                       ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"              
        echo -e " ${magenta}1)${reset} 系统信息查看"
        echo -e " ${magenta}2)${reset} 快捷键指南"
        echo -e " ${red}0)${reset} 返回主菜单"

        echo -e "${blue}$(printf '═%.0s' $(seq 1 60))${reset}"
        echo -en "${yellow}请输入选项编号 [ 例如：1 ]: ${reset}"
        read -rp "" choice
        case $choice in
            # 修复了中文分号问题
            1) show_system_info; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            2) show_shortcut_guide; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            0) echo -e "${green}→ 正在返回主菜单...${reset}";   break ;;
            *) echo -e "${red}✗ 无效选择，请重新输入！${reset}"; sleep 0.5 ;;
        esac
        echo -e "\n${yellow}按Enter键继续...${reset}"
        read -r
    done
}
# ====================== 系统信息子菜单功能 ======================
# 系统信息概览：显示系统、硬件、存储、网络等信息
show_system_info() {
    clear
     echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
     echo -e "${green}╔══════════════════════════════════════════════════════════╗"
     echo -e "║                         系统信息概览                      ║"
     echo -e "╚══════════════════════════════════════════════════════════╝${reset}"     
    # 系统基础信息
    echo -e "${cyan}操作系统:${reset} $(lsb_release -d | cut -f2-)" 
    echo -e "${cyan}内核版本:${reset} $(uname -r)"  
    echo -e "${cyan}系统时间:${reset} $(date)"  
    echo -e "${cyan}运行时间:${reset} $(uptime -p)"
    # 硬件信息
    echo -e "\n${cyan}CPU型号:${reset} $(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)"
    echo -e "${cyan}核心数量:${reset} $(grep -c "processor" /proc/cpuinfo)核" 
    # 读取并清理内存信息（修复Cached多值问题）
                  total_mem=$(grep '^MemTotal:' /proc/meminfo | awk '{print $2}' | sed 's/[^0-9]//g')
                  mem_free=$(grep '^MemFree:' /proc/meminfo | awk '{print $2}' | sed 's/[^0-9]//g')
                  buffers=$(grep '^Buffers:' /proc/meminfo | awk '{print $2}' | sed 's/[^0-9]//g')
                  # 关键修复：用^Cached:精确匹配单行，避免匹配到其他包含Cached的行
                  cached=$(grep '^Cached:' /proc/meminfo | awk '{print $2}' | sed 's/[^0-9]//g')
                  # 验证所有值都是有效的数字
                  if [ -n "$error_msg" ]; then
                      echo -e "${red}内存信息读取错误:$error_msg${reset}"

                      # 尝试兼容处理（如果Buffers或Cached为空则视为0）
                      if [ -z "$buffers" ] || ! [[ "$buffers" =~ ^[0-9]+$ ]]; then
                          buffers=0
                      fi
                      if [ -z "$cached" ] || ! [[ "$cached" =~ ^[0-9]+$ ]]; then
                          cached=0
                      fi

                      # 再次尝试基础计算（只要求total_mem和mem_free有效）
                      if [[ "$total_mem" =~ ^[0-9]+$ && "$mem_free" =~ ^[0-9]+$ ]]; then
                          used_mem=$((total_mem - mem_free - buffers - cached))
                          total_gb=$(awk -v total="$total_mem" 'BEGIN {printf "%.2f", total / 1024 / 1024}')
                          used_gb=$(awk -v used="$used_mem" 'BEGIN {printf "%.2f", used / 1024 / 1024}')
                          echo -e "${yellow}兼容模式内存使用:${reset} ${used_gb}G/${total_gb}G"
                      fi
                  else
                      # 计算使用的内存
                      used_mem=$((total_mem - mem_free - buffers - cached))

                      # 转换为GB显示
                      total_gb=$(awk -v total="$total_mem" 'BEGIN {printf "%.2f", total / 1024 / 1024}')
                      used_gb=$(awk -v used="$used_mem" 'BEGIN {printf "%.2f", used / 1024 / 1024}')

                      echo -e "${cyan}内存使用:${reset} ${used_gb}G/${total_gb}G"
                  fi

    # 存储信息
    echo -e "\n${cyan}磁盘使用:${reset}"
    df -Th
    # 显示器信息
    echo -e "\n${cyan}显示器信息:${reset}"
    xrandr | grep " connected"
    # 网络信息
    echo -e "\n${cyan}IP地址:${reset} $(hostname -I | awk '{print $1}')"
    # 移除按Enter返回，自动触发菜单跳转
    echo -e "\n${yellow}按Enter键继续...${reset}"
    read -r
}
# 多屏操作快捷键指南：显示常用快捷键
show_shortcut_guide() {
    clear
        echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                       多屏操作快捷键                     ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"     

    echo -e "${cyan}窗口管理：${reset}"
    echo -e "  Alt+Tab        - 窗口切换"
    echo -e "  Win+Tab        - 多任务视图"
    echo -e "  Win+方向键      - 窗口贴边"
    echo -e "  Ctrl+Win+←/→   - 工作区切换"
    echo -e "\n${cyan}多屏操作：${reset}"
    echo -e "  Super+P        - 显示模式切换"
    echo -e "  Win+Shift+←/→  - 窗口移动到相邻屏幕"
    echo -e "  Ctrl+Shift+←/→ - 窗口移动并最大化"
    echo -e "\n${cyan}系统操作：${reset}"
    echo -e "  Ctrl+Alt+T     - 打开终端"
    echo -e "  Alt+F2         - 运行命令"
    echo -e "  Ctrl+Alt+Del   - 系统锁定"

    echo -e "\n${yellow}按Enter键继续...${reset}"
    read -r
}

# 执行主函数 
system_info_menu
# 添加循环保护，防止意外退出
if [ $? -ne 0 ]; then
    echo -e "${red}菜单执行出错，3秒后返回主菜单...${reset}"
    sleep 3
fi